// #include "ndoe_config.h"

#include "json_handler.h"
#include <rapidjson/document.h> // 依赖rapidjson库
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/writer.h>
#include "log/syslog.h"
#include <fstream>

using namespace rapidjson;
using namespace equip_system;

//
#define TAG "CMqttConfig"

std::string CMqttConfig::serialize(const MqttConfig &data, vector<std::string> &param)
{
    return "";
}

// AJsonHandler 实现
bool CMqttConfig::read(const std::string &filename, MqttConfig &data, string &json_string)
{
    std::ifstream file(filename);
    if (!file.is_open())
    {
        ES_LOG(TAG, LEVEL_ERROR, "Failed to open config file: %s", filename.c_str());
        return false;
    }

    // 读取文件内容到字符串
    std::string content((std::istreambuf_iterator<char>(file)),
                        std::istreambuf_iterator<char>());

    // 解析JSON
    rapidjson::Document doc;
    if (doc.Parse(content.c_str()).HasParseError())
    {
        ES_LOG(TAG, LEVEL_ERROR, "Failed to parse config file");
        return false;
    }

    // 解析MQTT配置
    if (doc.HasMember("mqtt") && doc["mqtt"].IsObject())
    {
        const auto &mqttObj = doc["mqtt"];
        data.broker_ip = JsonHandler::_getStringValue(mqttObj, "broker_ip", "127.0.0.1");
        data.broker_port = JsonHandler::_getIntValue(mqttObj, "broker_port", 1883);
        data.protocol = JsonHandler::_getStringValue(mqttObj, "protocol", "tcp://");
        data.client_id = JsonHandler::_getStringValue(mqttObj, "client_id", "default_client");
        data.username = JsonHandler::_getStringValue(mqttObj, "username", "");
        data.password = JsonHandler::_getStringValue(mqttObj, "password", "");
        data.topic = JsonHandler::_getStringValue(mqttObj, "topic_prefix", "");
        data.cycle_delay = JsonHandler::_getIntValue(mqttObj, "cycle_delay", 10000);
        data.retry_delay = JsonHandler::_getIntValue(mqttObj, "retry_delay", 10000);
        data.keep_alive = JsonHandler::_getIntValue(mqttObj, "keep_alive", 60);
        data.timeout = JsonHandler::_getIntValue(mqttObj, "timeout", 5);
    }
    else
    {
        ES_LOG(TAG, LEVEL_WARNING, "MQTT config section not found, using defaults");
    }

    return true;
}

bool CMqttConfig::write(const std::string &filename, const MqttConfig &data)
{

    return true;
}
